from django import forms
from microerp.apps.base.models import Users
'''
用户登录表单
'''
#Define Login form
class SignInForm(forms.Form):
	email = forms.EmailField(required=True,error_messages={'required':u'邮箱不能为空','invalid':u'请输入正确的邮箱'})
	password = forms.CharField(required=True,error_messages={'required':u'密码不能为空','invalid':u'请输入正确的邮箱'})
	remember = forms.BooleanField(required=False)

	#验证模块
	def clean(self):
		#获取表单数据
		cleaned_data = self.cleaned_data

		#最好使用cleaned_data.get("email")替代cleaned_data["email"] 这样当传入空值 就不会报错
		data_email = cleaned_data.get("email")
		data_password = cleaned_data.get("password")
		if data_email:
			is_exist = Users.objects.filter(email=data_email,password=data_password).exists()
			if not is_exist:
				self._errors['password'] = self.error_class([u"用户名或密码错误!"])

		#无论做了什么验证 data始终要传回去，否则就失去form data了
		return cleaned_data

'''
定义注册form
'''
#Define Sign-up form
class SignUpForm(forms.Form):
	email = forms.CharField(max_length=20,required=True,
		error_messages={'required':u'邮箱不能为空','invalid':u'请输入正确的邮箱'})
	password1 = forms.CharField(max_length=16,min_length=6,required=True,
		error_messages={'required':u'密码不能为空','max_length':u'请输入至多16位数的密码','min_length':u'请输入至少6位数的密码'})
	password2 = forms.CharField(max_length=16,min_length=6,required=True,
		error_messages={'required':u'密码不能为空'})

	def clean(self):
		cleaned_data = self.cleaned_data
		data_email = self.cleaned_data.get('email')
		is_exist = Users.objects.filter(email=data_email).exists()
		if is_exist:
			self._errors['email'] = self.error_class([u"该邮箱已经被注册"])
		else:	
			data_password1 = self.cleaned_data.get('password1')
			data_password2 = self.cleaned_data.get("password2")
			if data_password1 != data_password2:
				self._errors['password1'] = self.error_class([u"两次输入的密码不一致"])
		return cleaned_data


